package xyz.blushyes.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.logging.log4j.util.Strings;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import xyz.blushyes.dao.CacheTestDao;
import xyz.blushyes.entity.CacheTest;
import xyz.blushyes.service.CacheTestService;

import java.util.concurrent.TimeUnit;
import java.util.random.RandomGenerator;

import static xyz.blushyes.constant.CacheConst.*;

@Service
@RequiredArgsConstructor
public class CacheTestServiceImpl extends ServiceImpl<CacheTestDao, CacheTest> implements CacheTestService {
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public Integer notCache(int number) {
        return lambdaQuery()
                .eq(CacheTest::getNumber, number)
                .oneOpt()
                .map(CacheTest::getId)
                .orElse(null);
    }

    @Override
    public Integer cacheNullObject(int number) {
        // 首先查缓存
        String key = CACHE_PREFIX + number;
        String cache = stringRedisTemplate.opsForValue().get(key);

        // 如果缓存不为空，则直接返回
        if (!Strings.isBlank(cache)) {
            return NULL_CACHE.equals(cache) ? null : Integer.parseInt(cache);
        }

        // 否则从数据库查找
        Integer id = notCache(number);

        // 并存入Redis
        stringRedisTemplate.opsForValue().set(key, null == id ? NULL_CACHE : id.toString(), CACHE_TTL + RandomUtil.randomInt(1, 10), TimeUnit.HOURS);
        return id;
    }

    @Override
    public Integer bloomFilter(int number) {
        return null;
    }
}

